package com.shw.shiro.realms;

import com.shw.bean.User;
import com.shw.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by shw on 2018-04-12.
 */
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;


    //认证的方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("----------->执行realm");
        //1.把authenticationToken转换为UsernamePasswordToken
        UsernamePasswordToken token= (UsernamePasswordToken) authenticationToken;
        //2.从usernamepasswordtoken中获取username
        String username = token.getUsername();
        char[] password = token.getPassword();
        System.out.println("原密码----------->"+password.toString());

        //3.调用数据库的方法，从数据库中查询username对应的记录
        User user = userService.selectUserByUsername(username);
        System.out.println("----------->"+user);
        //4.若用户不存在，抛出异常
        if(user==null){
            throw new UnknownAccountException("用户不存在");
        }
        //5.根据用户信息的情况，决定是否抛出其他的异常
        //被锁定的异常

        //6.根据用户的情况来构建AuthenticationInfo对象并返回
        //以下信息是从数据库中获取的
        //principal：认证的实体信息   可以是username，也可以是数据表对应的用户的实体类对象
        Object principal=user;
        //credentials：密码
        Object credentials=user.getPassword();
        //realmName：当前realm对象的name，调用父类的getName（）方法获取
        String realmName=getName();
        //盐值(使用用户名作为盐值)
        ByteSource credentialsSalt=ByteSource.Util.bytes(user.getUsername());

        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(principal,credentials,credentialsSalt,realmName);

        return info;
    }


    //授权会被回调的方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        System.out.println("授权--------->"+principalCollection);
        return null;
    }
}
